package ooseminar.parking;

import java.util.Collections;
import java.util.List;

import static java.util.Arrays.asList;

public class ParkingManager {
    protected List<ParkingLots> parkingLotsList;
    private ParkingLotsChooser chooser;
    protected List<ParkingManager> managerList = Collections.EMPTY_LIST;
    private static final String INDENT = "  ";

    public ParkingManager(ParkingLots... parkingLotsList) {
        this(new DefaultParkingLotChooser(), parkingLotsList);
    }

    public ParkingManager(List<ParkingManager> managers, ParkingLots... parkingLotses) {
        this(parkingLotses);
        this.managerList = Collections.unmodifiableList(managers);
    }

    public ParkingManager(ParkingLotsChooser chooser, ParkingLots... parkingLotsList) {
        this.parkingLotsList = asList(parkingLotsList);
        this.chooser = chooser;
    }

    public Object park(Car car) {
        for (ParkingManager manager : managerList) {
            Object ticket = manager.park(car);
            if (ticket != null)
                return ticket;
        }
        return chooser.chooseParkingLots(parkingLotsList).park(car);
    }

    public Car unpark(Object ticket) {
        for (ParkingManager manager : managerList) {
            Car car = manager.unpark(ticket);
            if (car != null)
                return car;
        }

        for (ParkingLots parkingLots : parkingLotsList) {
            Car car = parkingLots.unpark(ticket);
            if (car != null)
                return car;
        }
        return null;
    }

    public String Report() {
        StringBuilder builder = new StringBuilder("PM\n");

        for(ParkingLots lots : parkingLotsList){
            builder.append(INDENT).append(lots.Report()).append("\n");
        }

        for (ParkingManager parkingManager : managerList) {
            String[] reportLines = parkingManager.Report().split("\n");
            for (String report : reportLines) {
                builder.append(INDENT).append(report).append("\n");
            }
        }
        return builder.toString();
    }

}
